package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.common.DataResults;
import org.example.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/idiom")
@CrossOrigin(origins = "*")
public class DoUserController {

    @Autowired
    private UserService us;




    @RequestMapping("/user/login")
    public DataResults validateLogin2(@RequestBody User user){
        User one = us.getOne(new QueryWrapper<User>().eq("uacc", user.getUacc()));
        if(one!=null){
            if(one.getUpwd().equals(user.getUpwd())){
                return DataResults.success(one);
            }else{
                return DataResults.fail("账号或密码错误！");
            }
        }else{
            user.setScore(0);
            us.save(user);
            User newOne = us.getOne(new QueryWrapper<User>().eq("uacc", user.getUacc()));
            return DataResults.success(newOne);
        }
    }

    @RequestMapping("/game/saveScore")
    public DataResults saveScore(@RequestBody Map<String,Object> param){
        User u = us.getOne(new QueryWrapper<User>().eq("id", param.get("uid")));
        if(u != null){
            int newScore  = Integer.parseInt(param.get("score").toString());
            int oldScore = u.getScore();
            if(newScore>oldScore){
                us.update(
                        new User(){{
                            setScore(newScore);
                        }},
                        new QueryWrapper<User>().eq("id",param.get("uid"))
                );
                u=us.getOne(new QueryWrapper<User>().eq("id", param.get("uid")));
            }
        }
        return DataResults.success(u);

    }
//
    @RequestMapping("/game/list")
    public DataResults gameRankList(@RequestBody Map<String,Object> param){
//        User u = us.getOne(new QueryWrapper<User>().eq("id", param.get("uid")));
        List<User> rankList = us.getRankList();
//        rankList.add(u);
        return DataResults.success(rankList);
    }
}
